package com.whc.controller;

import com.whc.result.Result;
import com.whc.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author 韦红材
 * @ClassName CommonContoller
 * @data 2024/12/01 17:03
 * @Version V1.0
 **/
@RestController
@RequestMapping("/client/common")
@Api(tags = "公共接口")
@Slf4j
public class CommonContoller {
    @Autowired
    private AliOssUtil aliOssUtil;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> loadFile (MultipartFile file){
        log.info("开始上传文件{}",file);
        String originalFilename = file.getOriginalFilename();
//        String houzui=originalFilename.substring(originalFilename.indexOf("."));
//        String fileName=UUID.randomUUID()+houzui;
        try {
//            String upload = aliOssUtil.upload(file.getBytes(), fileName);
            String upload = aliOssUtil.upload(file.getBytes(), originalFilename);
            return Result.success(upload);
        } catch (IOException e) {
            log.info("文件上传失败");
        }
        return Result.error("文件上传失败");
    }
    @ApiOperation("上传多个文件")
    @PostMapping("/uploads")
    @PreAuthorize("hasAuthority('user')")
    public Result<List<String>> loadFiles (List<MultipartFile> files){
        log.info("开始上传文件{}",files);
        List<String> uploads=new ArrayList<>();
        for(MultipartFile file:files){
            String originalFilename = file.getOriginalFilename();
//            String houzui=originalFilename.substring(originalFilename.indexOf("."));
//            String fileName=UUID.randomUUID()+houzui;
            try {
//                String upload = aliOssUtil.upload(file.getBytes(), fileName);
                String upload = aliOssUtil.upload(file.getBytes(), originalFilename);
                uploads.add(upload);
            } catch (IOException e) {
                log.info("文件上传失败");
                Result.error("文件上传失败");
            }
        }
        return Result.success(uploads);
    }
}
